package cn.yuanqiao.archive.detection.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 *
 * @author ruoyi
 */
@Component
@ServerEndpoint("/websocket/{id}")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数1000
     */
    public static int socketMaxOnlineCount = 1000;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    public static ConcurrentHashMap<Long, WebSocketServer> webSocketSet = new ConcurrentHashMap<Long, WebSocketServer>();

    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam(value = "id") Long id, Session session) throws Exception
    {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            //WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        }
        else
        {
            // 添加用户
            this.session = session;
            webSocketSet.put(id, this);
            //WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", webSocketSet.size());
           // WebSocketUsers.sendMessageToUserByText(session, "连接成功");
      //      this.sendToMessageById(id,"连接成功");
           webSocketSet.get(id).sendMessage("连接成功");
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(@PathParam(value = "id") Long id,Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
      //  WebSocketUsers.remove(session.getId());

        webSocketSet.remove(id);

        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);


    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {}", sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);

        // 移出用户
     //   WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        if(message.indexOf(";")>-1) {
            Long id = Long.parseLong(message.split(";")[1]);
            String value=message.split(";")[0];
            if (value.equals("ping")) {
                webSocketSet.get(id).sendMessage("pong");

            }
        }
        String msg = message.replace("你", "我").replace("吗", "");
        //WebSocketUsers.sendMessageToUserByText(session, msg);
    }

    public void sendMessage(String message) throws IOException {
        synchronized (session) {
            getSession().getBasicRemote().sendText(message);
        }
    }



    /**
     * 给指定的人发送消息
     *
     * @param message
     */
    public  void sendToMessageById(Long id, String message) {
        try {
            if (webSocketSet.get(id) != null) {
                webSocketSet.get(id).sendMessage(message);
            } else {
                System.out.println("webSocketSet中没有此key，不推送消息");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Session getSession() {
        return session;
    }


}

